<?php
/**
 * Created by PhpStorm.
 * Script Name: Groupmember.php
 * Create: 2021/12/21 12:00
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use plugin\wechat\app\service\Bot as BotService;
use plugin\wechat\app\service\BotGroup as GroupService;
use plugin\wechat\app\model\BotMember;
use plugin\wechat\app\model\BotGroupmember as GM;
use plugin\wechat\app\TenantController;

class Botgroupmember extends TenantController
{
    /**
     * @var GM
     */
    protected $model;
    /**
     * @var BotMember
     */
    private $groupM;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->model = new GM();
        $this->groupM = new BotMember();
    }

    public function index()
    {
        $bot = \request()->botInfo;
        $group_id = input('group_id', 0);
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere(),
                ['bot_id' ,'=', $bot['id']],
                ['group_id' ,'=', $group_id]
            ];
            !empty($post_data['search_key']) && $where[] = ['nickname|group_nickname|wxid', 'like', '%' . $post_data['search_key'] . '%'];
            $query = $this->model->where($where);
            $total = $query->count();
            if (! $total) {
                $group = $this->groupM->find($group_id);
                $total = GroupService::pullGroupMembers($bot, $group);
            }
            $list = $query->page($post_data['page'], $post_data['limit'])
                ->select();
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => '昵称、备注名称']
        ])
            ->setDataUrl(url('index', ['group_id' => $group_id]))
            //->setTip("注意：当前的备注名称就是指实际微信通讯录当中您对该好友的备注")
            ->addTopButton('self', ['text'=>'同步群成员', 'href' => url('syncMembers', ['group_id' => $group_id]), 'data-ajax' => 1])
            ->addTableColumn(['title' => 'wxid', 'field' => 'wxid', 'minWidth' => 170])
            ->addTableColumn(['title' => '微信昵称', 'field' => 'nickname', 'minWidth' => 100])
            ->addTableColumn(['title' => '头像', 'field' => 'headimgurl', 'type' => 'picture', 'minWidth' => 100])
            ->addTableColumn(['title' => '群内昵称', 'field' => 'group_nickname'])
            ->addTableColumn(['title' => '微信号', 'field' => 'username'])
            ->addTableColumn(['title' => '操作', 'minWidth' => 150, 'type' => 'toolbar'])
            //->addRightButton('edit', ['title' => '设置备注名'])
            ->addRightButton('self', ['title' => '移出群聊','href' => url('removeMemberPost', ['id' => '__data_id__']),'class' => 'layui-btn layui-btn-xs layui-btn-danger','data-ajax' => 1, 'data-confirm' => 1]);

        return $builder->show();
    }

    /**
     * 移除群成员
     * @return \support\Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function removeMemberPost(){
        $bot = \request()->botInfo;
        $id = input('post.id');
        $friend = $this->model->alias('gm')
            ->join(request()->plugin . '_bot_member g', 'g.id=gm.group_id')
            ->where([
                ['gm.bot_id','=', $bot['id']],
                ['gm.id','=', $id],
                ['g.type' ,'=', BotService::GROUP]
            ])
            ->field(['g.wxid as group_wxid', 'gm.*'])
            ->find();
        if(! $friend){
            return $this->error('数据不存在');
        }
        $res = BotService::getRobotClient($bot)->removeGroupMember([
            'robot_wxid' => $bot['uin'],
            'group_wxid' => $friend['group_wxid'],
            'to_wxid' => $friend['wxid']
        ]);
        if($res['code']){
            $this->model->where($this->pk, $id)->delete();
            return $this->success('操作成功!');
        }else{
            return $this->error($res['errmsg']);
        }
    }

    /**
     * 同步好友数据
     * @return \support\Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function syncMembers(){
        $bot = \request()->botInfo;
        $group_id = input('group_id', 0);
        $group = $this->groupM->find($group_id);
        $total = GroupService::pullGroupMembers($bot, $group);
        return $this->success('此次同步到' . $total . '位群成员');
    }
}